const { pool, add, edit } = require('./baseModel.js')
const dayjs = require('dayjs')

exports.add = async (uid, fields) => {
    let totle_money = 0
    fields.foodList.forEach(item => {
        totle_money += item.price * 100 * item.count
    });
    let order_info = {
        uid: uid,
        submit_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        order_status: 0,
        order_money: totle_money,
        aid: fields.aid
    }
    // console.log(order_info);
    // 开启事务
    // await pool.query('start transaction')
    let info = await add('order_info', order_info)
    for (let item of fields.foodList) {
        await add('order_detail', {
            oid: info[0].insertId,
            fid: item.fid,
            count: item.count
        })
    }
    // 订单成功写入后删除购物车对应项
    let map = fields.foodList.map(item => item.id)
    console.log('订单成功，开始删除购物车');
    console.log(map);
    await pool.query("update shop_cart set isDel=1 where uid=? and id in (?);", [uid, map])
    // await pool.query('commit')
    return info;
}

exports.delete = async (id, uid) => {
    return edit('order_info', { isDel: 1 }, { id, uid })
}

exports.findById = async (id, uid) => {
    let result = await pool.query('select oi.id,oi.submit_time,oi.order_status,od.fid,od.count,f.food_name,f.price from order_info as oi left join order_detail as od on oi.id=od.oid left join food_info as f on od.fid=f.id where oi.isDel=0 and oi.id=? and oi.uid=?', [id, uid])
    return result[0]
}

exports.findByUid = async (uid, pageIndex = 1) => {
    // let result = await pool.query('select oi.id,oi.submit_time,oi.order_money,oi.order_status,od.fid,od.count,f.food_name,f.price from order_info as oi left join order_detail as od on oi.id=od.oid left join food_info as f on od.fid=f.id where oi.isDel=0 and oi.uid=? order by oi.id desc limit ?,10', [uid, (pageIndex - 1) * 10])
    let orders = await pool.query('select * from order_info where isDel=0 and uid=? order by id desc limit ?,10', [uid, (pageIndex - 1) * 10])
    for (const item of orders[0]) {
        let temp = await pool.query('select od.*,f.food_name,f.price from order_detail as od left join food_info as f on od.fid=f.id where od.isDel=0 and od.oid=?', [item.id])
        item.orderDetailList = temp[0]
    }
    return orders[0];
}

exports.pay = async (id, uid) => {
    return edit('order_info', { order_status: 1 }, { id, uid })
}